package com.apobates.jforum.grief.aurl.selector;

import com.apobates.jforum.grief.aurl.core.AUrlMeta;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 查询字符串选择器
 */
public class QueryStringSelector extends AUrlMetaGeneralSelector{

    public QueryStringSelector(AUrlMeta rawMeta) {
        super(rawMeta);
    }

    @Override
    public Collection<String> getResult() {
        final Map<String, List<String>> queryParams  = getRawMeta().getQueryParams();
        if (queryParams.isEmpty()) {
            return EMPTY.get();
        }
        StringBuilder queryBuilder = new StringBuilder();
        queryParams.forEach((name, values) -> {
            for (Object value : values) {
                if (queryBuilder.length() != 0) {
                    queryBuilder.append('&');
                }
                queryBuilder.append(name);
                if (value != null) {
                    queryBuilder.append('=').append(encodeParamValue(value.toString()));
                }
            }
        });
        return List.of(queryBuilder.toString());

    }

    private String encodeParamValue(String value){
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        }catch (Exception e){}
        return value;
    }
}
